import React, { useState, useEffect, useMemo } from 'react';
import { Table, Button, Space, Popconfirm, message, Tag, Avatar } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExportOutlined, ImportOutlined, UserOutlined } from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { useDictionary } from '@/hooks/useDictionary';
import type { TableConfig, FieldConfig, TableDataResponse, SearchDTO } from './types';

// 字典标签组件（用于表格中显示字典值对应的标签）
interface DictionaryLabelProps {
  value: any;
  dictionaryCode: string;
  fallbackValue?: any; // 如果字典没有找到，使用这个值
}

// 根据字典值自动设置颜色（常见状态值）
const getColorByValue = (value: string): string => {
  const lowerValue = String(value).toLowerCase();
  // 状态类字典值
  if (lowerValue.includes('active') || lowerValue.includes('启用') || lowerValue.includes('正常') || lowerValue.includes('成功')) {
    return 'success';
  }
  if (lowerValue.includes('inactive') || lowerValue.includes('禁用') || lowerValue.includes('停用') || lowerValue.includes('失败')) {
    return 'error';
  }
  if (lowerValue.includes('pending') || lowerValue.includes('待') || lowerValue.includes('审核')) {
    return 'warning';
  }
  if (lowerValue.includes('draft') || lowerValue.includes('草稿')) {
    return 'default';
  }
  // 默认颜色
  return 'blue';
};

const DictionaryLabel: React.FC<DictionaryLabelProps> = ({ value, dictionaryCode, fallbackValue }) => {
  const { getLabel, items } = useDictionary({ code: dictionaryCode });
  
  if (value === null || value === undefined) {
    return <Tag>-</Tag>;
  }
  
  const label = getLabel(String(value));
  // 如果字典中没有找到对应的标签（返回的是原值），使用 fallbackValue 或原值
  const displayValue = label === String(value) && items.length > 0 ? (fallbackValue || value) : label;
  
  // 如果 fallbackValue 是 React 元素（比如 Tag），直接返回
  if (React.isValidElement(fallbackValue)) {
    return fallbackValue;
  }
  
  // 使用 Tag 组件显示，并根据值设置颜色
  const color = getColorByValue(String(value));
  
  return <Tag color={color}>{displayValue}</Tag>;
};

interface DynamicTableProps {
  config: TableConfig;
  dataSource?: any[];
  loading?: boolean;
  onSearch?: (params: SearchDTO) => void;
  onCreate?: () => void;
  onEdit?: (record: any) => void;
  onDelete?: (id: any) => void;
  onBatchDelete?: (ids: any[]) => void;
  onExport?: (params: SearchDTO) => void;
  onImport?: (file: File) => void;
  customActions?: (record: any) => React.ReactNode;
  showToolbar?: boolean; // 是否显示工具栏（新增、导出等按钮）
  selectedRowKeys?: React.Key[]; // 外部控制的选中keys
  onSelectedRowKeysChange?: (keys: React.Key[]) => void; // 选中变化回调
}

export const DynamicTable: React.FC<DynamicTableProps> = ({
  config,
  dataSource = [],
  loading = false,
  onSearch,
  onCreate,
  onEdit,
  onDelete,
  onBatchDelete,
  onExport,
  onImport,
  customActions,
  showToolbar = true, // 默认显示工具栏
  selectedRowKeys: externalSelectedRowKeys,
  onSelectedRowKeysChange,
}) => {
  const [internalSelectedRowKeys, setInternalSelectedRowKeys] = useState<React.Key[]>([]);
  
  // 使用外部 selectedRowKeys 或内部状态
  const selectedRowKeys = externalSelectedRowKeys !== undefined ? externalSelectedRowKeys : internalSelectedRowKeys;
  const setSelectedRowKeys = onSelectedRowKeysChange || setInternalSelectedRowKeys;
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: config?.tableProps?.pagination && typeof config.tableProps.pagination === 'object'
      ? config.tableProps.pagination.pageSize || 10
      : 10,
    total: 0,
  });

  // 生成表格列
  const columns = useMemo<ColumnsType<any>>(() => {
    // 检查config和fields是否存在
    if (!config || !config.fields || !Array.isArray(config.fields)) {
      return [];
    }
    
    const cols: ColumnsType<any> = config.fields
      .filter(field => !field.table?.hidden)
      .map((field: FieldConfig) => {
        const tableConfig = { ...field.common, ...field.table };
        
        const column: any = {
          key: field.key,
          dataIndex: field.key,
          title: field.label,
          width: tableConfig.width,
          align: tableConfig.align || 'left',
          ellipsis: tableConfig.ellipsis ?? true,
          fixed: tableConfig.fixed,
        };
        
        // 处理排序 - sorter 必须是函数或 true/false，不能是其他类型
        if (tableConfig.sortable === true) {
          column.sorter = true;
        } else if (typeof tableConfig.sortable === 'function') {
          column.sorter = tableConfig.sortable;
        } else if (tableConfig.sortable === false || tableConfig.sortable === undefined) {
          // 不设置 sorter，表示不可排序
        } else {
          // 如果 sortable 是其他类型（如字符串），忽略它
          console.warn(`Invalid sortable value for field ${field.key}:`, tableConfig.sortable);
        }

        // 自定义渲染
        const renderConfig = tableConfig.render as any;
        const relationField = (tableConfig as any).relationField;
        
        // 确保 render 是函数，不能是字符串或其他类型
        if (renderConfig && typeof renderConfig === 'function') {
          column.render = renderConfig;
        } else {
          // 根据类型默认渲染
          column.render = (value: any, record: any, index: number) => {
            // 处理关联字段（如 role.name, department.name）
            if (renderConfig === 'relation' && relationField) {
              const fieldParts = relationField.split('.');
              let relationValue = record;
              
              for (const part of fieldParts) {
                if (relationValue && typeof relationValue === 'object') {
                  relationValue = relationValue[part];
                } else {
                  relationValue = null;
                  break;
                }
              }
              
              return relationValue !== null && relationValue !== undefined ? relationValue : '-';
            }
            
            if (value === null || value === undefined) {
              return '-';
            }

            // 优先检查字典配置
            const optionsConfig = tableConfig.optionsConfig || 
              (tableConfig.options ? { source: 'static' as const, options: tableConfig.options } : undefined);
            
            // 优先使用字典
            if (optionsConfig?.source === 'dictionary' && optionsConfig.dictionaryCode) {
              // 如果配置了 tag 渲染，作为后备方案
              const fallbackValue = renderConfig === 'tag' ? (
                (() => {
                  const tagColorMap = (tableConfig as any).tagColorMap || {};
                  const tagLabelMap = (tableConfig as any).tagLabelMap || {};
                  const color = tagColorMap[value] || 'default';
                  const label = tagLabelMap[value] || value;
                  return <Tag color={color}>{label}</Tag>;
                })()
              ) : undefined;
              
              return <DictionaryLabel value={value} dictionaryCode={optionsConfig.dictionaryCode} fallbackValue={fallbackValue} />;
            }

            switch (field.type) {
              case 'switch':
                return value ? <Tag color="success">是</Tag> : <Tag color="default">否</Tag>;
              case 'image':
                // 使用 Avatar 组件显示头像/图片
                const avatarSize = (tableConfig as any).size || 50;
                const avatarStyle = (tableConfig as any).avatarStyle || {};
                return (
                  <Avatar 
                    src={value || undefined} 
                    icon={<UserOutlined />}
                    size={avatarSize}
                    style={avatarStyle}
                  />
                );
              case 'date':
              case 'datetime':
                return value ? new Date(value).toLocaleString() : '-';
              case 'select':
                // 静态选项或 API 选项
                if (optionsConfig?.options) {
                  const option = optionsConfig.options.find((opt: any) => opt.value === value);
                  return option ? option.label : value;
                }
                
                // 兼容旧配置
                if (tableConfig.options) {
                  const option = tableConfig.options.find(opt => opt.value === value);
                  return option ? option.label : value;
                }
                
                // 如果没有字典配置，使用 Tag 渲染（如果配置了）
                if (renderConfig === 'tag') {
                  const tagColorMap = (tableConfig as any).tagColorMap || {};
                  const tagLabelMap = (tableConfig as any).tagLabelMap || {};
                  const color = tagColorMap[value] || 'default';
                  const label = tagLabelMap[value] || value;
                  return <Tag color={color}>{label}</Tag>;
                }
                
                return value;
              default:
                // 如果有选项，显示对应的label
                if (tableConfig.options) {
                  const option = tableConfig.options.find(opt => opt.value === value);
                  return option ? option.label : value;
                }
                return value;
            }
          };
        }

        return column;
      });

    // 添加操作列
    if (config.actions && (config.actions.update || config.actions.delete || config.actions.custom?.length)) {
      cols.push({
        title: '操作',
        key: 'actions',
        fixed: 'right',
        width: 150,
        render: (_, record) => (
          <Space size="small">
            {config.actions?.update && (
              <Button
                type="link"
                size="small"
                icon={<EditOutlined />}
                onClick={() => onEdit?.(record)}
              >
                编辑
              </Button>
            )}
            {config.actions?.delete && (
              <Popconfirm
                title="确定删除此项？"
                onConfirm={() => onDelete?.(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            )}
            {config.actions?.custom?.map(action => (
              <Button
                key={action.key}
                type={action.type || 'link'}
                size="small"
                icon={action.icon}
                onClick={() => action.onClick?.(record, selectedRowKeys as any[])}
              >
                {action.label}
              </Button>
            ))}
            {customActions?.(record)}
          </Space>
        ),
      });
    }

    return cols;
  }, [config, onEdit, onDelete, selectedRowKeys, customActions]);

  // 处理表格变化
  const handleTableChange = (
    newPagination: TablePaginationConfig,
    filters: any,
    sorter: any
  ) => {
    setPagination(newPagination);

    const searchParams: SearchDTO = {
      page: newPagination.current,
      pageSize: newPagination.pageSize,
    };

    if (sorter.field) {
      searchParams.sortBy = sorter.field;
      searchParams.sortOrder = sorter.order === 'descend' ? 'desc' : 'asc';
    }

    onSearch?.(searchParams);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的项');
      return;
    }
    onBatchDelete?.(selectedRowKeys as any[]);
    setSelectedRowKeys([]);
  };

  // 行选择配置
  const rowSelection = config.tableProps?.rowSelection
    ? {
        selectedRowKeys,
        onChange: setSelectedRowKeys,
        type: 'checkbox' as const,
      }
    : undefined;

  return (
    <div className="dynamic-table">
      {/* 工具栏 - 仅在 showToolbar 为 true 时显示 */}
      {showToolbar && (
        <div className="table-toolbar" style={{ marginBottom: 16 }}>
          <Space>
            {config.actions?.create && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={onCreate}
              >
                新增
              </Button>
            )}
            {config.actions?.batchDelete && selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除选中的 ${selectedRowKeys.length} 项？`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  icon={<DeleteOutlined />}
                >
                  批量删除 ({selectedRowKeys.length})
                </Button>
              </Popconfirm>
            )}
            {config.actions?.export && (
              <Button
                icon={<ExportOutlined />}
                onClick={() => onExport?.({ ...pagination })}
              >
                导出
              </Button>
            )}
            {config.actions?.import && (
              <Button
                icon={<ImportOutlined />}
                onClick={() => {
                  const input = document.createElement('input');
                  input.type = 'file';
                  input.accept = '.xlsx,.xls,.csv';
                  input.onchange = (e: any) => {
                    const file = e.target.files?.[0];
                    if (file) {
                      onImport?.(file);
                    }
                  };
                  input.click();
                }}
              >
                导入
              </Button>
            )}
          </Space>
        </div>
      )}

      {/* 表格 */}
      <Table
        bordered={config.tableProps?.bordered}
        size={config.tableProps?.size}
        showHeader={config.tableProps?.showHeader}
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        rowKey={config.tableProps?.rowKey || 'id'}
        rowSelection={rowSelection}
        pagination={pagination}
        onChange={handleTableChange}
        scroll={{ x: 'max-content' }}
      />
    </div>
  );
};

export default DynamicTable;
